#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ��ȡ��ǰ�ű��ļ�����Ŀ¼�ĸ�Ŀ¼�����������·��
import os
import sys
current_dir = os.path.dirname(os.path.abspath(__file__))
project_path = os.path.join(current_dir, '..')
sys.path.append(project_path)
sys.path.append(current_dir)
import gi
import cv2
import threading
import time
import warnings
import queue
import sys
gi.require_version('Gst', '1.0')
from gi.repository import Gst, GLib

def on_new_sample(sink):
    sample = sink.emit('pull-sample')
    buffer = sample.get_buffer()
    
    # ��� buffer �Ƿ���Ч
    if buffer:
        caps = sample.get_caps()
        structure = caps.get_structure(0)
        width = structure.get_int('width')[1]
        height = structure.get_int('height')[1]
        
        print(f"{width}, {height}")
        '''        
        print(f'{structure}')
        '''
    
        # ����һ�� mapinfo ������ӳ������
        success, mapinfo = buffer.map(Gst.MapFlags.READ)
        if success:
            # ��ȡӳ����ֽ�����
            data = mapinfo.data
            #print(f'frame len ={len(data)}')
            # �ļ�·��
            file_path = 'frame_by_soft_decode_of_h265file.bin'
            # ���ļ���д������
            with open(file_path, 'wb') as file:
                file.write(data)
            
            # ȡ��ӳ��
            buffer.unmap(mapinfo)    
    sys.exit(0)
    return Gst.FlowReturn.OK


def fetch_a_frame_from_file(filepath):
    Gst.init(None)
    
    pipeline = Gst.parse_launch(f'filesrc location={filepath} ! h265parse ! mppvideodec ! videoconvert ! appsink emit-signals=True max-buffers=1 drop=True sync=False')
    appsink = pipeline.get_by_name('appsink0')
    appsink.connect('new-sample', on_new_sample)
    
    pipeline.set_state(Gst.State.PLAYING)
    GLib.MainLoop().run()
    
def fetch_a_frame_from_stream(rtsp_addr):
    Gst.init(None)
    
    pipeline = Gst.parse_launch(f'rtspsrc location={rtsp_addr} latency=200 ! rtph265depay ! h265parse ! mppvideodec ! videoconvert ! appsink emit-signals=True max-buffers=1 drop=True sync=False')    
    appsink = pipeline.get_by_name('appsink0')
    appsink.connect('new-sample', on_new_sample)
    
    pipeline.set_state(Gst.State.PLAYING)
    GLib.MainLoop().run()

def is_rtsp_url(url):
    return url.startswith('rtsp://')

def main():
    # ��ӡ���д��ݵ������в���
    #print("�ű�����", sys.argv[0])
    #print("����������", len(sys.argv) - 1)
    #for i, arg in enumerate(sys.argv[1:], start=1):
    #    print(f"���� {i}: {arg}")
    if(is_rtsp_url(sys.argv[1])):
        fetch_a_frame_from_stream(sys.argv[1])
    else:
        fetch_a_frame_from_file(sys.argv[1])

if __name__ == "__main__":
    main()